package com.lestar.www.wuliancamtest.WulianCam;

import android.content.Context;
import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.Hashtable;

/**
 * User: EEE
 * Date: 2016/8/3
 * Time: 15:49
 */
public class CamUtils {

    public static Bitmap createQRImage(String qrdata, int qrwidth, int qrheight) {
        Bitmap bitmap = null;
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(qrdata,
                    BarcodeFormat.QR_CODE, qrwidth, qrheight, hints);
            int[] pixels = new int[qrwidth * qrheight];
            for (int y = 0; y < qrheight; y++) {
                for (int x = 0; x < qrwidth; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * qrwidth + x] = 0xff000000;
                    } else {
                        pixels[y * qrwidth + x] = 0xffffffff;
                    }
                }
            }
            bitmap = Bitmap.createBitmap(qrwidth, qrheight,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, qrwidth, 0, 0, qrwidth, qrheight);
        } catch (WriterException e) {
            e.printStackTrace();
            bitmap = null;
        }
        return bitmap;
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
